package top.anonyeast.util;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * token工具类
 *
 * @Author AnonyEast
 * @Date 2022-06-10
 * @Description
 */
public class TokenUtil {
    //HS256(HmacSHA256)密钥
    private static final String KEY = "EpidemicPrevention.anonyeast.top";

    /**
     * 签发token
     * @param userId
     * @return
     */
    public static String getToken(Long userId){
        DateTime now = DateTime.now();
        //有效期限:2小时
        DateTime expireTime = now.offsetNew(DateField.HOUR, 2);
        //JWT载荷信息:存放有效信息的地方
        Map<String, Object> payload = new HashMap<>();
        //签发时间
        payload.put(JWTPayload.ISSUED_AT,now);
        //生效时间
        payload.put(JWTPayload.NOT_BEFORE,now);
        //过期时间
        payload.put(JWTPayload.EXPIRES_AT,expireTime);
        //有效信息:userId
        payload.put("userId",userId);
        //创建签名算法为HS256(HmacSHA256)的JWT Token并返回
        return JWTUtil.createToken(payload,KEY.getBytes());
    }

    /**
     * 验证token
     * @param token
     * @return
     */
    public static boolean verifyToken(String token){
        try {
            JWT jwt = JWTUtil.parseToken(token);
            jwt.setKey(KEY.getBytes());
            //验证JWT是否有效，容忍时间为10秒
            return jwt.validate(10);
        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
            return false;
        }
    }

    /**
     * 获取用户userId
     * @param token
     * @return
     */
    public static Long getUserId(String token){
        try {
            JWT jwt = JWTUtil.parseToken(token);
            jwt.setKey(KEY.getBytes());
            return Long.parseLong(jwt.getPayload("userId").toString());
        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
            return null;
        }
    }
}
